-- Copyright (c) 2025 Huawei Technologies Co., Ltd.
-- openUBMC is licensed under Mulan PSL v2.
-- You can use this software according to the terms and conditions of the Mulan PSL v2.
-- You may obtain a copy of Mulan PSL v2 at:
--         http://license.coscl.org.cn/MulanPSL2
-- THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
-- EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
-- MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
-- See the Mulan PSL v2 for more details.
-- Description:
--   This class is responsible for canbus collection, specified functions are following:
--   1. Management for all canbus instances
--   2. Functional interfaces of canbus collection, such as batch sending, or statistics

local log = require 'mc.logging'
local canbus_collection = require 'canbus.collection'
local definition = require 'canbus.definition'
local common = require 'common'

local module = {}

local function send_property(msg)
    -- 在每个通道发送
    local collections = canbus_collection.get_instance().collections
    for k, v in pairs(collections) do
        local payload = definition.sync_property_payload_pattern:pack({
            cmd = definition.can_cmds.PROPERTY_SYNC_REQ,
            identifier = v.identifier,
            size = #msg,
            checksum = common.get_checksum(msg),
            datas = msg
        })
        if not payload then
            log:warn('canbus [%s] sync property payload generate failed.', k)
            goto continue
        end

        canbus_collection.get_instance():send(payload, k, definition.dest.BOARDCAST)
        ::continue::
    end
end

local can_cmds_to_format = {
    [definition.can_cmds.PROPERTY_SYNC_REQ] = send_property
}

function module.send_msg(cmd, ...)
    if not canbus_collection.get_instance().canbus_enabled then
        return
    end
    if not can_cmds_to_format[cmd] then
        log:error('send msg failed, wrong cmd [%s]', cmd)
        return
    end
    can_cmds_to_format[cmd](...)
end

return module